package logic

import (
	"context"
	"time"

	"mall/common/enumx"
	"mall/common/resultx"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/types/forum"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateCollectLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateCollectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCollectLogic {
	return &CreateCollectLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateCollectLogic) CreateCollect(in *forum.CreateCollectReq) (*forum.CreateCollectResp, error) {
	if in.ObjectId == 0 {
		return nil, resultx.StatusError(resultx.FORUM_REACTION_CONTENT_ID_INVALID, "")
	}

	if in.ObjectType == 0 {
		return nil, resultx.StatusError(resultx.FORUM_REACTION_TYPE_INVALID, "")
	}

	if in.VisitorId == 0 {
		return nil, resultx.StatusError(resultx.FORUM_REACTION_USER_ID_INVALID, "")
	}

	collect := &model.ForumUserCollect{
		UserID:     uint64(in.VisitorId),
		PlatformID: uint(in.PlatformId),
		ObjectID:   uint64(in.ObjectId),
		ObjectType: uint16(in.ObjectType),
		Status:     uint8(enumx.ObjectStatusAproved),
		// 不指定CreatedAt，避免被修改
		UpdatedAt: time.Now(),
	}

	if len(in.Meta) > 0 {
		for _, metum := range in.Meta {
			switch metum.Key {
			case "slug":
				collect.SorterValue1 = null.StringFrom(metum.Value)
			case "year":
				collect.SorterValue2 = null.StringFrom(metum.Value)
			case "minProductGems":
				collect.SorterValue3 = null.StringFrom(metum.Value)
			case "averageRating":
				collect.SorterValue4 = null.StringFrom(metum.Value)
			case "popularity":
				collect.SorterValue5 = null.StringFrom(metum.Value)
			case "season":
				collect.FilterValue3 = null.StringFrom(metum.Value)
			case "gender":
				collect.FilterValue5 = null.StringFrom(metum.Value)
			}
		}
	}

	_, err := l.svcCtx.ForumUser.UpdateCollect(l.ctx, collect)
	if err != nil {
		return nil, err
	}

	return &forum.CreateCollectResp{}, nil
}
